import { AppAisle } from "@lib/alen-helper/node/appAisle";
import { RunTime } from "../../runtime";

type Handlers = AppAisle.CmdHandlers<Runtime.Controller.Window.BaseCmdData>;

export class WindowCmdHandlers implements Handlers {
    constructor(
        public readonly options: {},
        public readonly runTime: RunTime,
    ) {
        this.runTime.sendEvent(
            this.runTime.windowController, 'close', data => this.runTime.getApp(data.item.appid), 'window_event_close',
            data => ({ appid: data.item.appid, id: data.item.id, data: data.data }),
            (data, e) => ({ item: e.data.item, data: data.data }),
        );
        this.runTime.sendEvent(
            this.runTime.windowController, 'ready', data => this.runTime.getApp(data.item.appid), 'window_event_ready',
            data => ({ appid: data.item.appid, id: data.item.id }),
        );
        this.runTime.sendEvent(
            this.runTime.windowController, 'show', data => this.runTime.getApp(data.item.appid), 'window_event_show',
            data => ({ appid: data.item.appid, id: data.item.id }),
        );
        this.runTime.sendEvent(
            this.runTime.windowController, 'hide', data => this.runTime.getApp(data.item.appid), 'window_event_hide',
            data => ({ appid: data.item.appid, id: data.item.id }),
        );
    }
    private _getApp(aisle: AppAisle<AppAisle.Cmds>) {
        const app = this.runTime.getApp(aisle);
        if (!app || !app.id) throw new Error('找不到APP');
        return app;
    }
    //============
    window_build: Handlers['window_build'] = (data, aisle) => {
        const app = this._getApp(aisle);
        return this.runTime.windowController.start(app.id!, data.data.param.options);
    }

    window_show: Handlers['window_show'] = (data, aisle) => {
        const app = this._getApp(aisle);
        return this.runTime.windowController.show(app.id!, data.data.param.id);
    }

    window_hide: Handlers['window_hide'] = (data, aisle) => {
        const app = this._getApp(aisle);
        return this.runTime.windowController.hide(app.id!, data.data.param.id);
    }

    window_close: Handlers['window_close'] = (data, aisle) => {
        const app = this._getApp(aisle);
        return this.runTime.windowController.close(app.id!, data.data.param.id);
    }
}